package com.demo.web;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.demo.enums.ResponseStatus;
import com.demo.exception.LoginException;
import com.demo.util.JwtUtil;

import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @description 认证拦截器 非Security
 *
 */
@Order(2)
@Slf4j
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (request.getMethod().equals(HttpMethod.OPTIONS.name())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        String url = getUri(request);
        if (url.startsWith("sso")) {
            return true;
        }
        String token = (String)request.getHeader("Authorization");
        if (StringUtils.isBlank(token)) {
            // 未登录
            throw new LoginException(ResponseStatus.UNAUTHORIATION);
        }
        Claims claims = JwtUtil.parseToken(token.substring(6).trim());
        if (claims == null) {
            throw new LoginException(ResponseStatus.TOKEN_EXPIRED);
        }
        Date exp = JwtUtil.getExpireDate(claims);
        if (exp.getTime() <= System.currentTimeMillis()) {
            throw new LoginException(ResponseStatus.TOKEN_EXPIRED);
        }

        return true;
    }

    // 获取资源的路径,去掉ContextPath
    private String getUri(HttpServletRequest request) {
        String uri = request.getContextPath();
        String url = request.getRequestURI();
        // String url3 = request.getServletPath();
        if (uri.equals("/")) {
            return url;
        } else {
            return url.replace(uri, "");
        }
    }

}
